NowCode:HJ9 提取不重复的整数

题目:提取不重复的整数

描述

输入一个 int 型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。

保证输入的整数最后一位不是 0 。

数据范围: 1≤𝑛≤10^8

输入描述:

输入一个int型整数

输出描述:

按照从右向左的阅读顺序,返回一个不含重复数字的新的整数

示例

1
2
3
4
5
输入:
9876673

输出:
37689

题解1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main() {
int input = 0;
cin >> input;
string str = to_string(input);
string ret;
for (int i = str.size() - 1; i >= 0; i--) {
if (ret.find(str[i]) == std::string::npos) {
ret += str[i];
}
}
cout << stoi(ret);
}

题解2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<set>
using namespace std;

int main() {
int input;
cin >> input;
set<int> cnt;
int ans = 0;

while (input > 0) {
int temp = input % 10;
if (cnt.count(temp) == 0) {
ans = ans * 10 + temp;
cnt.insert(temp);
}
input /= 10;
}

cout << ans << endl;
return 0;
}

思路

我的第一感觉是利用取余不断拿出最后一位,后来想到转成字符串处理再转回整数,即题解1

题解2参考了他人解法,用set记录,用取余开路,用除等于循环

此题很好

strinf::find用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// string::find
#include <iostream> // std::cout
#include <string> // std::string

int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");

// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';

found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';

found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';

found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';

// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';

return 0;
}
1
2
3
4
5
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.